package com.dingding.service.impl;

import com.dingding.common.Const;
import com.dingding.common.ServerResponse;
import com.dingding.common.TokenCache;
import com.dingding.dao.UserMapper;
import com.dingding.pojo.User;
import com.dingding.service.IUserService;
import com.dingding.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.util.Properties;
import java.util.UUID;

/**
 * Created by 33293 on 2017/8/17.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {

        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0 ){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        int status = userMapper.selectStatusByUsername(username);
        if(status == 0){
            return ServerResponse.createByErrorMessage("邮箱未激活，请激活邮箱");
        }

        String md5Password = MD5Util.MD5EncodeUtf8(password);

        User user = userMapper.selectLogin(username,md5Password);

        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }

        userMapper.setLastLogin(username);

        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }

    public ServerResponse<String> register(User user){
        ServerResponse validResponse;
        //校验用户名、邮箱、手机号是否存在
        validResponse = this.checkValid(user.getName(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getPhone(), Const.PHONE);
        if(!validResponse.isSuccess()){
            return validResponse;
        }


        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }

        //todo 给邮箱发送验证码
        String code = UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.EMAIL_CODE+user.getEmail(),code);
        emailTest(user.getEmail(),code);

        return ServerResponse.createBySuccessMessage("注册成功,请激活邮箱后使用");

    }

    public ServerResponse<String> setStatus(String email,String code){
        if(org.apache.commons.lang3.StringUtils.isBlank(code)){
            return ServerResponse.createByErrorMessage("参数错误,需要传递激活码");
        }
        ServerResponse validResponse = this.checkValid(email,Const.EMAIL);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String emailCode = TokenCache.getKey(TokenCache.EMAIL_CODE+email);
        if(org.apache.commons.lang3.StringUtils.isBlank(emailCode)){
            return ServerResponse.createByErrorMessage("激活码无效或者过期");
        }
        int status = userMapper.selectStatusByEmail(email);
        if(status == 1){
            return ServerResponse.createByErrorMessage("邮箱已激活，请勿重复激活");
        }

        if(org.apache.commons.lang3.StringUtils.equals(code,emailCode)){
            int rowCount = userMapper.setStatus(email);
            if(rowCount > 0){
                return ServerResponse.createBySuccessMessage("邮箱激活成功");
            }
        }else{
            return ServerResponse.createByErrorMessage("激活码有误");
        }
        return ServerResponse.createByErrorMessage("激活失败");
    }


    public ServerResponse<String> checkValid(String str,String type){
        //type 参数不为 " " 或 空
        if (StringUtils.isNotBlank(type)){
            //开始校验
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMessage("邮箱已存在");
                }
            }
            if(Const.PHONE.equals(type)){
                int resultCount = userMapper.checkPhone(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMessage("手机号已存在");
                }
            }
        }else{
            return ServerResponse.createByErrorMessage("参数错误");
        }

        return ServerResponse.createBySuccessMessage("校验成功");
    }

    public ServerResponse<String> selectQuestion(String username){

        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selecQuestionByUserName(username);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    public ServerResponse<String> checkAnswer(String username,String question,String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        if(resultCount>0){
            //说明问题及问题答案是这个用户的,并且是正确的
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }

    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        if(org.apache.commons.lang3.StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误,token需要传递");
        }
        ServerResponse validResponse = this.checkValid(username,Const.USERNAME);
        if(validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(org.apache.commons.lang3.StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }

        if(org.apache.commons.lang3.StringUtils.equals(forgetToken,token)){
            String md5Password  = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);

            if(rowCount > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else{
            return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
        //防止横向越权,要校验一下这个用户的旧密码,一定要指定是这个用户.因为我们会查询一个count(1),如果不指定id,那么结果就是true啦count>0;
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }

        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    public ServerResponse<User> updateInformation(User user){
        //username是不能被更新的
        //email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");
        }
        //手机号校验
        resultCount = userMapper.checkEmailByUserId(user.getPhone(),user.getId());
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("手机号已存在,请更换手机号再尝试更新");
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setNickName(user.getNickName());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        //todo 名称转id
        updateUser.setSubjectId(user.getSubjectId());
        updateUser.setSchoolId(user.getSchoolId());
        //todo 图片
        updateUser.setPictureUrl(user.getPictureUrl());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    public ServerResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    //backend

    public ServerResponse checkAdminRole(User user){
        if (user != null && user.getRole() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    /**
     *
     * @author heziqi jar <!-- JavaMail相关依赖 --> + <dependency> +
     *         <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> +
     *         <version>1.4.7</version> + </dependency> + <dependency> +
     *         <groupId>javax.activation</groupId> +
     *         <artifactId>activation</artifactId> + <version>1.1.1</version> +
     *         </dependency>
     */
    public void emailTest(String email,String code){
        // 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        String from = "hjytest1@163.com";// 发件人电子邮箱
        String host = "smtp.163.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

        Properties properties = System.getProperties();// 获取系统属性

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        try {
            // QQ邮箱需要下面这段代码，163邮箱不需要
//			MailSSLSocketFactory sf = new MailSSLSocketFactory();
//			sf.setTrustAllHosts(true);
//			properties.put("mail.smtp.ssl.enable", "true");
//			properties.put("mail.smtp.ssl.socketFactory", sf);

            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("hjytest1@163.com", "wshjy123"); // 发件人邮箱账号、授权码
                }//这里的授权码和登录密码不同，qq/网易的授权码需要在客户端查看
            });

            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject("账号激活");
            // 2.4设置邮件内容
            String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3>" +
                    "<a href='http://localhost:8080/user/set_status.do?email="+ email + "&code="
                    + code + "'>http://localhost:8080/user/set_status.do?email="+ email + "&code="
                    + code + "</href></h3></body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);
            System.out.println("邮件成功发送!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
